const express = require('express');
const { body, query, param } = require('express-validator');
const { validationResult } = require('express-validator');
const User = require('../models/User');
const { auth, optionalAuth } = require('../middleware/auth');

const router = express.Router();

/**
 * @route   GET /api/users
 * @desc    获取用户列表
 * @access  Public
 */
router.get('/', optionalAuth, async (req, res) => {
  try {
    const { page = 1, limit = 10, search } = req.query;
    const skip = (page - 1) * limit;

    let query = { isActive: true };
    
    if (search) {
      query.$or = [
        { username: { $regex: search, $options: 'i' } },
        { name: { $regex: search, $options: 'i' } }
      ];
    }

    const users = await User.find(query)
      .select('username name avatar bio location isVerified followersCount followingCount createdAt')
      .sort({ followersCount: -1 })
      .skip(skip)
      .limit(parseInt(limit));

    const total = await User.countDocuments(query);

    res.json({
      success: true,
      data: {
        users,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total,
          pages: Math.ceil(total / limit)
        }
      }
    });

  } catch (error) {
    console.error('获取用户列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

/**
 * @route   GET /api/users/{userId}
 * @desc    获取用户信息
 * @access  Public
 */
router.get('/:userId', [
  param('userId').isMongoId().withMessage('无效的用户ID')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '请求参数验证失败',
        errors: errors.array()
      });
    }

    const user = await User.findById(req.params.userId)
      .populate('followers', 'username name avatar')
      .populate('following', 'username name avatar')
      .select('-password -refreshToken');

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      data: { user }
    });

  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

/**
 * @route   PUT /api/users/profile
 * @desc    更新用户资料
 * @access  Private
 */
router.put('/profile', auth, [
  body('name').optional().isLength({ min: 2, max: 50 }).withMessage('姓名长度必须在2-50个字符之间'),
  body('bio').optional().isLength({ max: 200 }).withMessage('个人简介最多200个字符'),
  body('avatar').optional().isURL().withMessage('头像必须是有效的URL'),
  body('location.city').optional().isLength({ max: 50 }).withMessage('城市名称最多50个字符'),
  body('location.country').optional().isLength({ max: 50 }).withMessage('国家名称最多50个字符'),
  body('location.coordinates').optional().isArray({ min: 2, max: 2 }).withMessage('坐标必须是包含经度和纬度的数组'),
  body('preferences.language').optional().isIn(['zh', 'en', 'el']).withMessage('语言设置无效'),
  body('preferences.theme').optional().isIn(['light', 'dark', 'auto']).withMessage('主题设置无效')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '输入数据验证失败',
        errors: errors.array()
      });
    }

    const userId = req.user.userId;
    const updateData = req.body;

    // 验证坐标格式
    if (updateData.location?.coordinates) {
      const [lng, lat] = updateData.location.coordinates;
      if (lng < -180 || lng > 180 || lat < -90 || lat > 90) {
        return res.status(400).json({
          success: false,
          message: '坐标范围无效'
        });
      }
    }

    const user = await User.findByIdAndUpdate(
      userId,
      { $set: updateData },
      { new: true, runValidators: true }
    ).select('-password -refreshToken');

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      message: '资料更新成功',
      data: { user }
    });

  } catch (error) {
    console.error('更新用户资料错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

/**
 * @route   POST /api/users/follow
 * @desc    关注用户
 * @access  Private
 */
router.post('/follow', auth, [
  body('targetUserId').isMongoId().withMessage('无效的目标用户ID')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '请求参数验证失败',
        errors: errors.array()
      });
    }

    const userId = req.user.userId;
    const { targetUserId } = req.body;

    // 检查目标用户是否存在
    const targetUser = await User.findById(targetUserId);
    if (!targetUser) {
      return res.status(404).json({
        success: false,
        message: '目标用户不存在'
      });
    }

    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    const result = await user.followUser(targetUserId);

    res.json({
      success: true,
      message: '关注成功',
      data: {
        newFollowingCount: result.newFollowingCount,
        targetFollowersCount: result.targetFollowersCount
      }
    });

  } catch (error) {
    console.error('关注用户错误:', error);
    
    if (error.message === '已经关注了该用户' || error.message === '不能关注自己') {
      return res.status(400).json({
        success: false,
        message: error.message
      });
    }

    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

/**
 * @route   POST /api/users/unfollow
 * @desc    取消关注用户
 * @access  Private
 */
router.post('/unfollow', auth, [
  body('targetUserId').isMongoId().withMessage('无效的目标用户ID')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '请求参数验证失败',
        errors: errors.array()
      });
    }

    const userId = req.user.userId;
    const { targetUserId } = req.body;

    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    const result = await user.unfollowUser(targetUserId);

    res.json({
      success: true,
      message: '取消关注成功',
      data: {
        newFollowingCount: result.newFollowingCount,
        targetFollowersCount: result.targetFollowersCount
      }
    });

  } catch (error) {
    console.error('取消关注用户错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

/**
 * @route   GET /api/users/nearby
 * @desc    查找附近的用户
 * @access  Private
 */
router.get('/nearby', auth, [
  query('lng').isFloat({ min: -180, max: 180 }).withMessage('经度必须在-180到180之间'),
  query('lat').isFloat({ min: -90, max: 90 }).withMessage('纬度必须在-90到90之间'),
  query('maxDistance').optional().isInt({ min: 1000, max: 100000 }).withMessage('距离范围必须在1000米到100000米之间')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '请求参数验证失败',
        errors: errors.array()
      });
    }

    const { lng, lat, maxDistance = 50000 } = req.query;
    const currentUserId = req.user.userId;

    const nearbyUsers = await User.findNearbyUsers(lng, lat, maxDistance);

    // 排除当前用户
    const filteredUsers = nearbyUsers.filter(user => 
      user._id.toString() !== currentUserId
    );

    res.json({
      success: true,
      data: {
        users: filteredUsers,
        count: filteredUsers.length,
        searchParameters: { lng: parseFloat(lng), lat: parseFloat(lat), maxDistance: parseInt(maxDistance) }
      }
    });

  } catch (error) {
    console.error('查找附近用户错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

/**
 * @route   GET /api/users
 * @desc    搜索用户
 * @access  Public
 */
router.get('/', [
  query('search').optional().isLength({ min: 1 }).withMessage('搜索关键词不能为空'),
  query('limit').optional().isInt({ min: 1, max: 50 }).withMessage('限制数量必须在1-50之间'),
  query('skip').optional().isInt({ min: 0 }).withMessage('跳过数量必须大于等于0')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '请求参数验证失败',
        errors: errors.array()
      });
    }

    const { search, limit = 10, skip = 0 } = req.query;
    
    let query = { isActive: true };
    
    if (search) {
      query.$or = [
        { username: { $regex: search, $options: 'i' } },
        { name: { $regex: search, $options: 'i' } },
        { email: { $regex: search, $options: 'i' } }
      ];
    }

    const users = await User.find(query)
      .select('-password -refreshToken')
      .sort({ followersCount: -1, createdAt: -1 })
      .limit(parseInt(limit))
      .skip(parseInt(skip));

    const total = await User.countDocuments(query);

    res.json({
      success: true,
      data: {
        users,
        pagination: {
          total,
          limit: parseInt(limit),
          skip: parseInt(skip),
          hasMore: (parseInt(skip) + parseInt(limit)) < total
        }
      }
    });

  } catch (error) {
    console.error('搜索用户错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

/**
 * @route   GET /api/users/{userId}/followers
 * @desc    获取用户粉丝列表
 * @access  Public
 */
router.get('/:userId/followers', [
  param('userId').isMongoId().withMessage('无效的用户ID'),
  query('limit').optional().isInt({ min: 1, max: 50 }).withMessage('限制数量必须在1-50之间'),
  query('skip').optional().isInt({ min: 0 }).withMessage('跳过数量必须大于等于0')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '请求参数验证失败',
        errors: errors.array()
      });
    }

    const { userId } = req.params;
    const { limit = 20, skip = 0 } = req.query;

    const user = await User.findById(userId)
      .populate({
        path: 'followers',
        select: 'username name avatar bio followersCount',
        options: {
          limit: parseInt(limit),
          skip: parseInt(skip),
          sort: { followersCount: -1 }
        }
      });

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      data: {
        followers: user.followers,
        total: user.followersCount,
        pagination: {
          limit: parseInt(limit),
          skip: parseInt(skip),
          hasMore: (parseInt(skip) + parseInt(limit)) < user.followersCount
        }
      }
    });

  } catch (error) {
    console.error('获取粉丝列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

/**
 * @route   GET /api/users/{userId}/following
 * @desc    获取用户关注列表
 * @access  Public
 */
router.get('/:userId/following', [
  param('userId').isMongoId().withMessage('无效的用户ID'),
  query('limit').optional().isInt({ min: 1, max: 50 }).withMessage('限制数量必须在1-50之间'),
  query('skip').optional().isInt({ min: 0 }).withMessage('跳过数量必须大于等于0')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '请求参数验证失败',
        errors: errors.array()
      });
    }

    const { userId } = req.params;
    const { limit = 20, skip = 0 } = req.query;

    const user = await User.findById(userId)
      .populate({
        path: 'following',
        select: 'username name avatar bio followersCount',
        options: {
          limit: parseInt(limit),
          skip: parseInt(skip),
          sort: { followersCount: -1 }
        }
      });

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      data: {
        following: user.following,
        total: user.followingCount,
        pagination: {
          limit: parseInt(limit),
          skip: parseInt(skip),
          hasMore: (parseInt(skip) + parseInt(limit)) < user.followingCount
        }
      }
    });

  } catch (error) {
    console.error('获取关注列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

module.exports = router; 